{% extends "base.html" %}

{% block title %}课程管理 - 学生选课系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-book me-2"></i>课程管理</h2>
    <div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCourseModal">
            <i class="fas fa-plus me-1"></i>添加课程
        </button>
    </div>
</div>

<!-- 课程列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">课程列表</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover" id="coursesTable">
                <thead>
                    <tr>
                        <th>课程代码</th>
                        <th>课程名称</th>
                        <th>学分</th>
                        <th>授课教师</th>
                        <th>容量</th>
                        <th>已选人数</th>
                        <th>上课时间</th>
                        <th>上课地点</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 课程数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加课程模态框 -->
<div class="modal fade" id="addCourseModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加新课程</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addCourseForm">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">课程代码 *</label>
                            <input type="text" class="form-control" name="course_code" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">课程名称 *</label>
                            <input type="text" class="form-control" name="course_name" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">学分 *</label>
                            <input type="number" class="form-control" name="credits" min="1" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">授课教师</label>
                            <input type="text" class="form-control" name="teacher">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">容量限制</label>
                            <input type="number" class="form-control" name="capacity" min="0">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">上课时间</label>
                            <input type="text" class="form-control" name="schedule" placeholder="例如：周一 1-2节">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">上课地点</label>
                            <input type="text" class="form-control" name="location">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">课程描述</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addCourse()">添加课程</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
// 页面加载时获取课程数据
document.addEventListener('DOMContentLoaded', function() {
    loadCourses();
});

// 加载课程列表
async function loadCourses() {
    try {
        const response = await fetch('/api/courses');
        if (!response.ok) {
            throw new Error('获取课程列表失败');
        }
        const courses = await response.json();
        renderCoursesTable(courses);
    } catch (error) {
        console.error('加载课程列表失败:', error);
        alert('加载课程列表失败: ' + error.message);
    }
}

// 渲染课程表格
function renderCoursesTable(courses) {
    const tbody = document.querySelector('#coursesTable tbody');
    tbody.innerHTML = '';
    
    if (courses.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="9" class="text-center text-muted py-4">
                    <i class="fas fa-inbox fa-2x mb-2"></i>
                    <p>暂无课程数据</p>
                </td>
            </tr>
        `;
        return;
    }
    
    courses.forEach(course => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${course.course_code || '-'}</td>
            <td>${course.course_name || '-'}</td>
            <td>${course.credits || '0'}</td>
            <td>${course.teacher || '-'}</td>
            <td>${course.capacity > 0 ? course.capacity : '无限制'}</td>
            <td>
                <span class="${course.capacity > 0 && course.enrolled >= course.capacity ? 'text-danger' : 'text-success'}">
                    ${course.enrolled || 0}
                </span>
            </td>
            <td>${course.schedule || '-'}</td>
            <td>${course.location || '-'}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewCourse('${course._id}')">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-outline-info" onclick="editCourse('${course._id}')">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-outline-danger" onclick="deleteCourse('${course._id}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 添加课程
async function addCourse() {
    const form = document.getElementById('addCourseForm');
    const formData = new FormData(form);
    
    const courseData = {
        course_code: formData.get('course_code'),
        course_name: formData.get('course_name'),
        credits: parseInt(formData.get('credits')),
        teacher: formData.get('teacher'),
        schedule: formData.get('schedule'),
        location: formData.get('location'),
        capacity: parseInt(formData.get('capacity')) || 0,
        description: formData.get('description')
    };
    
    try {
        const response = await fetch('/api/courses', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(courseData)
        });
        
        if (response.ok) {
            const result = await response.json();
            alert('课程添加成功！');
            // 使用Bootstrap原生方法隐藏模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addCourseModal'));
            modal.hide();
            form.reset();
            loadCourses(); // 重新加载课程列表
        } else {
            const error = await response.json();
            throw new Error(error.error || '添加课程失败');
        }
    } catch (error) {
        console.error('添加课程失败:', error);
        alert('添加课程失败: ' + error.message);
    }
}

// 查看课程详情
function viewCourse(courseId) {
    window.location.href = `/course-detail/${courseId}`;
}

// 编辑课程
function editCourse(courseId) {
    window.location.href = `/edit-course/${courseId}`;
}

// 删除课程
async function deleteCourse(courseId) {
    if (!confirm('确定要删除这个课程吗？此操作不可恢复。')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/courses/${courseId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            alert('课程删除成功！');
            loadCourses(); // 重新加载课程列表
        } else {
            const error = await response.json();
            throw new Error(error.error || '删除课程失败');
        }
    } catch (error) {
        console.error('删除课程失败:', error);
        alert('删除课程失败: ' + error.message);
    }
}
</script>
{% endblock %}
